import { createAction } from 'redux-actions'
import * as T from './actionTypes'
import axios from 'axios'
import _ from 'lodash'

export let articleGet = createAction(T.ARTICLE_GET,
  (param) => axios.get('/api/v0.1/articles?_sort=date&_order=DESC&_limit=10' + param).then((response) => {
    return {...response}
  })
)

export let articleAdd = createAction(T.ARTICLE_ADD, data =>
  axios.post('/api/v0.1/articles', data)
)

export let detailGet = createAction(T.DETAIL_GET, id => {
  return axios
    .all([
      axios.get(`/api/v0.1/articles?id=${id}`),
      axios.get(`/api/v0.1/answers?questionId=1&_limit=10`)
    ])
    .then(
      axios.spread((question, answers) => {
        console.log(question)
        console.log(answers)
        const answerIds = _.map(answers.data, 'id')
        const questionMap = question.data[0]
        const answerMap = _.mapKeys(answers.data, 'id')
        return {
          questionMap,
          answerMap,
          answerIds
        }
      })
    )
})

export let answerLike = createAction(T.ANSWER_LIKE, (id, userId) => {
  return axios.patch(`/api/v0.1/answers/${id}`, {
    praise: 1
  }).then(res => {
    return {
      id,
      userId
    }
  })
})
